package com.wosiliujing.learning.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wosiliujing.learning.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * session销毁监听
 * @author 刘靖
 * @date 2019-10-08 15:08
 */
@Slf4j
@AllArgsConstructor
@WebListener
class SessionListener implements HttpSessionListener {
    private final RedisTemplate redisTemplate;
    private final TokenStore tokenStore;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("session 创建:{}",se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        String sessionId = event.getSession().getId();
        log.info("sessionId 销毁:{}",sessionId);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Object token = redisTemplate.opsForValue().get(SecurityConstants.SESSION_REDIS_KEY+sessionId);
        if(token != null){
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token.toString());
            if(ObjectUtil.isNotEmpty(oAuth2AccessToken)&& StrUtil.isNotBlank(oAuth2AccessToken.getValue())){
                tokenStore.removeAccessToken(oAuth2AccessToken);
                tokenStore.removeRefreshToken(oAuth2AccessToken.getRefreshToken());
            }
        }
        redisTemplate.delete(SecurityConstants.SESSION_REDIS_KEY+sessionId);
    }
}
